package com.cloudinnov.controller.api;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.Size;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cloudinnov.aop.SystemLog;
import com.cloudinnov.dao.PredictionRuleTableDao;
import com.cloudinnov.logic.AuthUserLogic;
import com.cloudinnov.logic.ControlSolutionLogic;
import com.cloudinnov.logic.EquipmentsLogic;
import com.cloudinnov.logic.LightDetectLogic;
import com.cloudinnov.logic.PredictionRuleLogLogic;
import com.cloudinnov.logic.PredictionRuleTableLogic;
import com.cloudinnov.logic.RealTimeDataLogic;
import com.cloudinnov.logic.impl.PredictionRuleTableLogicImpl;
import com.cloudinnov.model.AuthUsers;
import com.cloudinnov.model.Companies;
import com.cloudinnov.model.ControlSolution;
import com.cloudinnov.model.ControlSolutionConfig;
import com.cloudinnov.model.EquipmentArea;
import com.cloudinnov.model.Equipments;
import com.cloudinnov.model.EquipmentsAttr;
import com.cloudinnov.model.PageModel;
import com.cloudinnov.model.PredictionContacter;
import com.cloudinnov.model.PredictionRuleLog;
import com.cloudinnov.model.PredictionRuleTable;
import com.cloudinnov.task.mq.FireMQConsumer;
import com.cloudinnov.utils.CodeUtil;
import com.cloudinnov.utils.CommonUtils;
import com.cloudinnov.utils.JudgeNullUtil;
import com.cloudinnov.utils.TcpClientUtil;
import com.cloudinnov.websocket.PredictionAlarmWebsocket;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.std.SerializableSerializer;
import com.github.pagehelper.Page;

import scala.util.parsing.combinator.testing.Str;

/**
 * @author guochao
 * @date 2016年2月17日上午11:55:55
 * @email chaoguo@cloudinnov.com
 * @remark 设备controller
 * @version
 */
@Controller
@RequestMapping("/webapi/equipment")
public class EquipmentController extends BaseController {
	static final Logger LOG = LoggerFactory.getLogger(EquipmentController.class);
	
	@Autowired
	private EquipmentsLogic equipmentsLogic;
	@Autowired
	private AuthUserLogic authUserLogic;
	@Autowired
	private RealTimeDataLogic realTimeDataLogic;
	@Autowired
	LightDetectLogic lightDetectLogic;
	@Autowired
	ControlSolutionLogic controlSolutionLogic;
	@Autowired
	PredictionRuleTableLogic predictionRuleTableLogic;
	@Autowired
	PredictionRuleTableDao predictionRuleTableDao;
	@Autowired
	private PredictionRuleLogLogic predictionRuleLogLogic;
	
	/**
	 * save
	 * 
	 * @Description: 保存设备
	 * @param @param
	 *            equipment
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @return
	 * @param @throws
	 *            JsonGenerationException
	 * @param @throws
	 *            JsonMappingException
	 * @param @throws
	 *            IOException 参数
	 * @return JSONPObject 返回类型
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "设备管理", methods = "设备信息保存")
	public void save(Equipments equipment, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws JsonGenerationException, JsonMappingException, IOException {
		String userType = getUserInfo(request).get(USER_TYPE);
		String companyCode = getUserInfo(request).get(COM_CODE);
		if (userType.equals(CommonUtils.CUSTORER_TYPE)) {
			equipment.setCustomerCode(companyCode);
		}
		// 二进制流转化为图片，并保存
		String base64S = equipment.getImageUrl();
		if (base64S != "" && base64S != "null") {
			String newImg = storeBase64(base64S, request);
			equipment.setImageUrl(newImg);
		}
		equipment.setOemCode(getUserInfo(request).get(OEM_CODE));
		int result = equipmentsLogic.save(equipment);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = returnJsonAllRequest(request, response, map, result, "");
		response.getWriter().println(returnData);
	}

	/**
	 * saveOtherLanguage
	 * 
	 * @Description: 添加设备其他语言信息
	 * @param @param
	 *            equipment
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @throws
	 *            JsonGenerationException
	 * @param @throws
	 *            JsonMappingException
	 * @param @throws
	 *            IOException 参数
	 * @return void 返回类型
	 */
	@RequestMapping(value = "/saveOtherLanguage")
	@ResponseBody
	@SystemLog(module = "设备管理", methods = "保存其他语言")
	public void saveOtherLanguage(Equipments equipment, HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		String returnData = null;
		equipment.setLanguage(equipment.getOtherLanguage());
		int result = equipmentsLogic.saveOtherLanguage(equipment);
		Map<String, Object> map = new HashMap<String, Object>();
		if (result == 1) {
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().println(returnData);
	}

	@RequestMapping(value = "/updateOtherLanguage", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "设备管理", methods = "修改其他语言")
	public void updateOtherLanguage(Equipments equipment, HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 获取oemCode
		equipment.setLanguage(equipment.getOtherLanguage());
		int result = equipmentsLogic.updateOtherLanguage(equipment);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = returnJsonAllRequest(request, response, map, result, "");
		response.getWriter().println(returnData);
	}

	/**
	 * delete
	 * 
	 * @Description: 根据code 或 id 删除设备（status = 9）
	 * @param @param
	 *            equipmentCode
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @param
	 *            model
	 * @param @return
	 * @param @throws
	 *            JsonGenerationException
	 * @param @throws
	 *            JsonMappingException
	 * @param @throws
	 *            IOException 参数
	 * @return JSONPObject 返回类型
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "设备管理", methods = "设备信息删除")
	public void delete(Equipments equipment, HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		int result = equipmentsLogic.delete(equipment);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = returnJsonAllRequest(request, response, map, result, "");
		response.getWriter().println(returnData);
	}

	/**
	 * update
	 * 
	 * @Description: 更新设备 code字段必须传
	 * @param @param
	 *            equipment
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @param
	 *            model
	 * @param @return
	 * @param @throws
	 *            JsonGenerationException
	 * @param @throws
	 *            JsonMappingException
	 * @param @throws
	 *            IOException 参数
	 * @return JSONPObject 返回类型
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "设备管理", methods = "设备信息修改")
	public void update(Equipments equipment, HttpServletRequest request, HttpServletResponse response, Model model)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 二进制流转化为图片，并保存
		String base64S = equipment.getImageUrl();
		if (base64S != "" && base64S != "null") {
			String newImg = storeBase64(base64S, request);
			equipment.setImageUrl(newImg);
		}
		int result = equipmentsLogic.update(equipment);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = returnJsonAllRequest(request, response, map, result, "");
		response.getWriter().println(returnData);
	}

	/**
	 * list
	 * 
	 * @Description: 分页查询设备列表
	 * @param @param
	 *            index
	 * @param @param
	 *            size
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @param
	 *            model
	 * @param @return
	 * @param @throws
	 *            JsonGenerationException
	 * @param @throws
	 *            JsonMappingException
	 * @param @throws
	 *            IOException 参数
	 * @return JSONPObject 返回类型
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public void listPage(int index, int size, Equipments equipment, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws IOException {
		if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.OEM_TYPE)) {
			equipment.setOemCode(getUserInfo(request).get(OEM_CODE));
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.CUSTORER_TYPE)) {
			equipment.setCustomerCode(getUserInfo(request).get(COM_CODE));
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.AGENT_TYPE)) {
			equipment.setAgentCode(getUserInfo(request).get(COM_CODE));
		}
		if (equipment.getState() != null) {
			equipment.setCurrentStates(Arrays.asList(equipment.getState().split(",")));
		}
		Page<Equipments> equipments = equipmentsLogic.selectListPage(index, size, equipment, false);
		Map<String, Object> map = new HashMap<String, Object>();
		if (equipments != null) {
			map.put("list", equipments);
			map.put("total", equipments.getTotal());
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().print(returnData);
		} else {
			response.getWriter().print(returnJsonAllRequest(request, response, map, ERROR, ""));
		}
	}

	/**
	 * 查询设备列表 无分页
	 * 
	 * @param equipment
	 * @param request
	 * @param response
	 * @param session
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping(value = "/listnopage")
	@ResponseBody
	public void list(Equipments equipment, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		equipment.setOemCode(getUserInfo(request).get(OEM_CODE));
		List<Equipments> equipments = equipmentsLogic.selectList(equipment, true);
		Map<String, Object> map = new HashMap<String, Object>();
		if (equipments != null) {
			map.put("list", equipments);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().print(returnData);
		} else {
			response.getWriter().print(returnJsonAllRequest(request, response, map, ERROR, ""));
		}
	}

	/**
	 * select
	 * 
	 * @Description: 根据code查询相应设备信息
	 * @param @param
	 *            equipment
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @param
	 *            model
	 * @param @return
	 * @param @throws
	 *            JsonGenerationException
	 * @param @throws
	 *            JsonMappingException
	 * @param @throws
	 *            IOException 参数
	 * @return JSONPObject 返回类型
	 */
	@RequestMapping(value = "/select")
	@ResponseBody
	public void select(Equipments equipment, HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		if (equipment.getOtherLanguage() != null && equipment.getOtherLanguage() != "") {
			equipment.setLanguage(equipment.getOtherLanguage());
		}
		Equipments result = equipmentsLogic.select(equipment);
		Map<String, Object> map = new HashMap<String, Object>();
		if (result != null) {
			map.put("model", result);
			response.getWriter().print(returnJsonAllRequest(request, response, map, SUCCESS, ""));
		} else {
			response.getWriter().print(returnJsonAllRequest(request, response, map, ERROR, ""));
		}
	}

	/**
	 * selectEquipmentTotalByCustomerId
	 * 
	 * @Description: 获取客户下的所有设备数量
	 * @param @param
	 *            customerId
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @return
	 * @param @throws
	 *            JsonGenerationException
	 * @param @throws
	 *            JsonMappingException
	 * @param @throws
	 *            IOException 参数
	 * @return JSONPObject 返回类型
	 */
	@RequestMapping(value = "/selectEquipmentTotalByCustomerId")
	@ResponseBody
	public void selectEquipmentTotalByCustomerId(String customerCode, HttpServletRequest request,
			HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException {
		int result = equipmentsLogic.selectEquipmentTotalByCustomerCode(customerCode);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("model", result);
		String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		response.getWriter().println(returnData);
	}

	/**
	 * listByCustomer
	 * 
	 * @Description: 根据客户code 查询该客户下的所有设备总数
	 * @param @param
	 *            customerId
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @param
	 *            model
	 * @param @return
	 * @param @throws
	 *            JsonGenerationException
	 * @param @throws
	 *            JsonMappingException
	 * @param @throws
	 *            IOException 参数
	 * @return JSONPObject 返回类型
	 */
	@RequestMapping(value = "/listByCustomer")
	@ResponseBody
	public void listByCustomer(Equipments equipment, HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		if (equipment.getCustomerCode() == null || equipment.getCustomerCode().equals("")) {
			equipment.setCustomerCode(getUserInfo(request).get(COM_CODE));
		}
		List<Equipments> equipments = equipmentsLogic.listByCustomer(equipment);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = "";
		if (equipments != null) {
			map.put("list", equipments);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().print(returnData);
	}

	@RequestMapping(value = "/listByCustomers")
	@ResponseBody
	public void listByCustomers(String language, String customerCodes, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String[] codes = null;
		if (customerCodes != null && customerCodes != "") {
			codes = customerCodes.split(",");
		}
		List<Equipments> equipments = equipmentsLogic.listByCustomers(language, codes);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = "";
		if (equipments != null) {
			map.put("list", equipments);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().print(returnData);
	}

	/**
	 * search
	 * 
	 * @Description: 设备列表搜索方法
	 * @param country
	 * @param province
	 * @param city
	 * @param brand
	 * @param model
	 * @param key
	 * @param request
	 * @param response
	 * @param session
	 * @param JsonGenerationException
	 * @param JsonMappingException
	 * @param IOException
	 *            参数
	 * @return void 返回类型
	 */
	@RequestMapping(value = "/search", method = RequestMethod.POST)
	@ResponseBody
	public void search(int index, int size, String country, String province, String city, String categoryCode,
			String model, String key, String language, String customerCode, String sectionCode, String type,
			HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {

		Page<Equipments> result = equipmentsLogic.search(index, size, country, province, city, categoryCode, key,
				sectionCode, language, type);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = "";
		if (result != null && result.size() > 0) {
			map.put("list", result);
		}
		map.put("total", result.getTotal());
		returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		response.getWriter().println(returnData);
		
		/*Page<Equipments> result = null;
		String returnData = "";
		Map<String, Object> map = new HashMap<String, Object>();
		// 其他设备的一般查询结果
		result = equipmentsLogic.search(index, size, country, province, city, categoryCode, key, sectionCode, language,
				type);
		if (result != null && result.size() > 0) {
			// 修改后的对象存放集合
			List<Equipments> equipments = null;
			// 被修改的对象的索引值
			List<Integer> indexs = new ArrayList<>();
			// 遍历结果中的能见度检测器
			for (int i = 0; i < result.size(); i++) {
				if ("NJDJCQ".equals(result.get(i).getCategoryCode())) {
					// 获取所有能见度的equipment的equipCode
					String equipCode = result.get(i).getCode();
					// 先通过equipCode的值查询数据库,获取该设备的ip和port
					List<EquipmentsAttr> EquipmentsAttrs = lightDetectLogic.selectLightByEquipCode(equipCode);
					for (EquipmentsAttr equipmentsAttr : EquipmentsAttrs) {
						if ("ip".equals(equipmentsAttr.getCustomTag())) {
							String ip = equipmentsAttr.getValue();
							boolean pingResult = false;
							try {
								// 调用TcpClientUtil的ping(ip,port)方法,判断是否ping通,是:3;否:0
								pingResult = TcpClientUtil.ping(ip);
							} catch (Exception e) {
								e.printStackTrace();
							}
							if (pingResult) {
								// 修改equipment的CurrentState的值
								result.get(i).setCurrentState(3);
								// 添加修改的对象到新的集合中
								equipments.add(result.get(i));
								indexs.add(i);
							}
						}
					}
				}
			}
			// 发现有修改过的对象时,走这一步
			if (indexs.size() > 0) {
				// 删除被修改,且原值中存有的
				for (int i = 0; i < indexs.size(); i++) {
					result.remove(indexs.get(i));
				}
				// 添加新修改的到里面
				for (int i = 0; i < equipments.size(); i++) {
					result.add(equipments.get(i));
				}
			}
			map.put("list", result);
			map.put("total", result.getTotal());
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			map.put("list", result);
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().println(returnData);*/
	}

	@RequestMapping(value = "/oemContactList")
	@ResponseBody
	public void customerContactList(PageModel page, String type, String customerCode, String language,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<AuthUsers> userList = null;
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> result = new HashMap<String, Object>();
		if (customerCode == null) {
			map.put("oemCode", getUserInfo(request).get(OEM_CODE));
		} else {
			map.put("comCode", customerCode);
		}
		map.put("language", language);
		map.put("type", type);
		String returnData = "";
		if (page.getIndex() != null) {
			map.put("index", page.getIndex());
			map.put("size", page.getSize());
			Page<AuthUsers> pageList = authUserLogic.selectOemUserList(page.getIndex(), page.getSize(), map);
			if (pageList != null) {
				result.put("list", pageList);
				result.put("total", pageList.getTotal());
				returnData = returnJsonAllRequest(request, response, result, SUCCESS, "");
			} else {
				returnData = returnJsonAllRequest(request, response, result, ERROR, "");
			}
		} else {
			userList = authUserLogic.selectOemUserList(map);
			if (userList != null) {
				result.put("list", userList);
				returnData = returnJsonAllRequest(request, response, result, SUCCESS, "");
			} else {
				returnData = returnJsonAllRequest(request, response, result, ERROR, "");
			}
		}
		response.getWriter().println(returnData);
	}

	/**
	 * 我的设备列表 select
	 * 
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @param
	 *            model
	 * @param @throws
	 *            IOException 参数
	 * @return void 返回类型
	 */
	@RequestMapping("/selectmyequipment")
	@ResponseBody
	public void selectMyEquipment(Equipments equipment, int index, int size, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		/**
		 * 查询我的设备列表
		 */
		equipment.setCustomerPerson(getUserInfo(request).get(USER_CODE));
		Page<Equipments> equipments = equipmentsLogic.selectEquipmentsByUser(equipment, index, size);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", equipments);
		map.put("total", equipments.getTotal());
		String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		response.getWriter().print(returnData);
	}

	/**
	 * 获取设备状态数量统计
	 * 
	 * @Title: getEquipmentStatusCount
	 * @Description: 运行设备数量，停机设备数量，故障设备数量，离线设备数量
	 * @param equipment
	 * @param request
	 * @param response
	 * @throws IOException
	 * @return: void
	 */
	@RequestMapping("/getEquipmentStateCount")
	@ResponseBody
	public void getEquipmentStateCount(@Valid Companies company, BindingResult result, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		if (CommonUtils.isEmpty(company.getOemCode())) {
			company.setOemCode(getUserInfo(request).get(OEM_CODE));
		}
		company.setCurrentState(CommonUtils.EQU_STATE_NORMAL);
		int equipmentsNormal = equipmentsLogic.selectEquipmentStates(company);
		company.setCurrentState(CommonUtils.EQU_STATE_FAULT);
		int equipmentsFault = equipmentsLogic.selectEquipmentStates(company);
		company.setCurrentState(CommonUtils.EQU_STATE_NO_SET_PARAME);
		int equipmentsStop = equipmentsLogic.selectEquipmentStates(company);
		company.setCurrentState(CommonUtils.EQU_STATE_OFFLINE);
		int equipmentsOffline = equipmentsLogic.selectEquipmentStates(company);
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("equipmentsNormal", equipmentsNormal);
		model.put("equipmentsFault", equipmentsFault);
		model.put("equipmentsStop", equipmentsStop);
		model.put("equipmentsOffline", equipmentsOffline);
		map.put("model", model);
		String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		response.getWriter().print(returnData);
	}

	@RequestMapping("/getEquipmentListByState")
	@ResponseBody
	public void getEquipmentListByState(Companies company, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		if (CommonUtils.isEmpty(company.getOemCode())) {
			company.setOemCode(getUserInfo(request).get(OEM_CODE));
		}
		List<Equipments> list = equipmentsLogic.getEquipmentListByState(company);
		Map<String, Object> map = new HashMap<String, Object>();
		if (list != null && list.size() > 0) {
			map.put("list", list);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().print(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().print(returnData);
		}
	}

	@RequestMapping(value = "/copyEquipments", method = RequestMethod.POST)
	@ResponseBody
	public void copyEquipments(@Valid Equipments equipments, BindingResult error, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// 校验没有通过
		if (error.hasErrors()) {
			String errorMsg = getErrors(error);
			response.getWriter().println(errorMsg);
			return;
		}
		int returnCode = equipmentsLogic.copyEquipments(equipments);
		Map<String, Object> map = new HashMap<String, Object>();
		if (returnCode >= CommonUtils.SUCCESS_NUM) {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().print(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().print(returnData);
		}
	}

	@RequestMapping(value = "/getState", method = RequestMethod.GET)
	@ResponseBody
	public void selectState(Equipments equipments, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Equipments model = equipmentsLogic.select(equipments);
		Map<String, Object> map = new HashMap<String, Object>();
		if (model != null) {
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("state", model.getCurrentState() != null ? model.getCurrentState() : 1);
			data.put("type", 1);
			data.put("text", "雨天路滑");
			map.put("data", data);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().print(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().print(returnData);
		}
	}

	@RequestMapping(value = "/getEquListByCateCode", method = RequestMethod.POST)
	@ResponseBody
	public void selectEquListByCateCode(Equipments equipments, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		List<Equipments> list = equipmentsLogic.selectEquListByCateCode(equipments);
		Map<String, Object> map = new HashMap<String, Object>();
		if (list != null) {
			map.put("list", list);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().print(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().print(returnData);
		}
	}

	@RequestMapping(value = "/getEquListByCateCodeList", method = RequestMethod.POST)
	@ResponseBody
	public void selectEquListByCateCodeList(Equipments equipments, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		List<Equipments> listInfo = equipmentsLogic.selectEquiClassifyAndEquipments(equipments);
		String returnData = "";
		HashMap<String, Object> map = new HashMap<String, Object>();
		boolean isSuccess = false;
		for (Equipments equip : listInfo) {
			if (equip.getCategoryCode().equals(equipments.getCategoryCode())) {
				map.put("list", equip.getEquipmensInfo());
				isSuccess = true;
				break;
			}
		}
		if (isSuccess) {
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().println(returnData);
	}

	/***
	 * 根据路段code查询设备信息
	 * 
	 * @param sectionCode
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "selectEquipmentsBySeCode", method = RequestMethod.GET)
	@SystemLog(module = "设备管理", methods = "根据路段code查询设备信息")
	public void selectEquipmentsBySeCode(Equipments equipments, int index, int size, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Page<Equipments> equiInfo = equipmentsLogic.selectEquipmentsBySeCode(equipments, index, size);
		String returnData = "";
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (equiInfo.size() != 0) {
			map.put("list", equiInfo);
			map.put("total", equiInfo.getTotal());
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().println(returnData);
	}

	@RequestMapping(value = "/getIndexTypeValue", method = RequestMethod.GET)
	public void selectIndexTypeValue(Equipments model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> data = realTimeDataLogic.selectRealtimeIndexTypeDataByEquipment(model);
		Map<String, Object> map = new HashMap<String, Object>();
		if (JudgeNullUtil.iMap(data)) {
			map.put("equCode", model.getCode());
			map.put("data", data);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().print(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().print(returnData);
		}
	}

	@RequestMapping(value = "/selectCameraAreaEquipments", method = RequestMethod.GET)
	@SystemLog(module = "监控区域管理", methods = "查询路段下的枪式摄像机的方法")
	public void selectCameraAreaEquipments(Equipments equipments, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String returnData = "";
		Map<String, Object> map = new HashMap<String, Object>();
		List<Equipments> cameraEquipments = equipmentsLogic.selectCameraAreaEquipments(equipments);
		if (JudgeNullUtil.iList(cameraEquipments)) {
			map.put("data", cameraEquipments);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().print(returnData);
	}

	@RequestMapping(value = "/selectTriggerEquipmentsBySection", method = RequestMethod.GET)
	@SystemLog(module = "监控区域管理", methods = "查询路段下某事故区下的触发设备方法")
	public void selectTriggerEquipmentsBySection(Equipments equipments, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String returnData = "";
		Map<String, Object> map = new HashMap<String, Object>();
		List<Equipments> triggerEquipments = equipmentsLogic.selectTriggerEquipmentsBySection(equipments);
		if (JudgeNullUtil.iList(triggerEquipments)) {
			map.put("data", triggerEquipments);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().print(returnData);

	}

	@RequestMapping(value = "/insertEquipmentArea", method = RequestMethod.POST)
	@SystemLog(module = "添加监控区域", methods = "添加监控区域方法,完善equipment_area表内容")
	public void insertEquipmentArea(EquipmentArea equipmentArea, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String returnData = "";
		Map<String, Object> map = new HashMap<String, Object>();

		boolean result = equipmentsLogic.insertEquipmentArea(equipmentArea);
		if (result) {
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			map.put("message", "添加的某个触发设备信息有误,导致添加部分错误!");
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().print(returnData);

	}

	@RequestMapping(value = "/updateEquipmentArea", method = RequestMethod.POST)
	@SystemLog(module = "监控区域管理", methods = "添加摄像区域和触发设备的关联关系表方法")
	public void updateEquipmentArea(EquipmentArea equipmentArea, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String returnData = "";
		Map<String, Object> map = new HashMap<String, Object>();
		boolean result = equipmentsLogic.updateEquipmentArea(equipmentArea);
		if (result) {
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			map.put("message", "添加的某个触发设备信息有误,导致添加部分错误!");
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().print(returnData);
	}

	@RequestMapping(value = "/deleteEquipmentArea", method = RequestMethod.POST)
	@SystemLog(module = "监控区域管理", methods = "添加摄像区域和触发设备的关联关系表方法")
	public void deleteEquipmentArea(EquipmentArea equipmentArea, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String returnData = "";
		Map<String, Object> map = new HashMap<String, Object>();
		boolean result = equipmentsLogic.deleteEquipmentArea(equipmentArea);
		if (result) {
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			map.put("message", "添加的某个触发设备信息有误,导致添加部分错误!");
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().print(returnData);
	}

	@RequestMapping(value = "/selectEquipmentAreaSection", method = RequestMethod.GET)
	@SystemLog(module = "监控区域管理", methods = "查询监控区域和触发设备的关联关系表中的路段方法")
	public void selectEquipmentAreaSection(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String returnData = "";
		Map<String, Object> map = new HashMap<String, Object>();

		List<EquipmentArea> equipmentAreas = equipmentsLogic.selectEquipmentAreaSection();

		if (JudgeNullUtil.iList(equipmentAreas)) {
			map.put("data", equipmentAreas);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().print(returnData);
	}

	@RequestMapping(value = "/selectEquipmentArea", method = RequestMethod.GET)
	@SystemLog(module = "监控区域管理", methods = "添加摄像区域和触发设备的关联关系表方法")
	public void selectEquipmentArea(EquipmentArea equipmentArea, int index, int size, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String returnData = "";
		Map<String, Object> map = new HashMap<String, Object>();
		// 对传入的参数重新进行字符编码
		if (equipmentArea != null && equipmentArea.getSectionName() != null) {
			String sectionName = new String(equipmentArea.getSectionName().getBytes("iso-8859-1"), "utf-8");
			equipmentArea.setSectionName(sectionName);
		}

		Page<EquipmentArea> equipmentAreas = equipmentsLogic.selectEquipmentArea(equipmentArea, index, size);

		if (JudgeNullUtil.iList(equipmentAreas)) {
			map.put("data", equipmentAreas);
			map.put("total", equipmentAreas.getTotal());
			returnData = JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect);
		} else {
			returnData = "监控区域查询为空,请检查!";
		}
		response.getWriter().print(returnData);
	}

	@RequestMapping(value = "/selectSignleEquipmentArea", method = RequestMethod.GET)
	@SystemLog(module = "监控区域管理", methods = "添加摄像区域和触发设备的关联关系表方法")
	public void selectSignleEquipmentArea(EquipmentArea equipmentArea, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String returnData = "";
		Map<String, Object> map = new HashMap<String, Object>();
		// 对传入的参数重新进行字符编码
		if (equipmentArea != null && equipmentArea.getSectionName() != null) {
			String sectionName = new String(equipmentArea.getSectionName().getBytes("iso-8859-1"), "utf-8");
			equipmentArea.setSectionName(sectionName);
		}

		EquipmentArea equipmentAreas = equipmentsLogic.selectSignleEquipmentArea(equipmentArea);

		if (equipmentAreas != null) {
			map.put("data", equipmentAreas);
			returnData = JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect);
		} else {
			returnData = "监控区域查询为空,请检查!";
		}
		response.getWriter().print(returnData);
	}

	@RequestMapping(value = "/selectAllClassifyTunnel", method = RequestMethod.GET)
	@SystemLog(module = "隧道信息查询", methods = "查询该系统中的所有隧道的基本信息")
	public void selectAllClassifyTunnel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String returnData = "";
		Map<String, Object> map = new HashMap<String, Object>();
		// 查询所有隧道和隧道下的事故区域
		List<Equipments> allClassifyTunnels = equipmentsLogic.selectAllClassifyTunnelsAndAccidentArea();

		if (JudgeNullUtil.iList(allClassifyTunnels)) {
			map.put("data", allClassifyTunnels);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().print(returnData);
	}
	
	@RequestMapping(value = "/selectCameraAreaAndTriggerEquipment", method = RequestMethod.GET)
	@SystemLog(module = "隧道信息查询", methods = "查询确定隧道下某个事故区域的监控区域和它下面的触发设备")
	public void selectCameraAreaAndTriggerEquipment(Equipments equipments, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String returnData = "";
		Map<String, Object> map = new HashMap<String, Object>();
		// 查询确定隧道下某个事故区域的监控区域和它下面的触发设备
		List<EquipmentArea> equipmentAreas = equipmentsLogic.selectCameraAreaAndTriggerEquipment(equipments);
		
		if (JudgeNullUtil.iList(equipmentAreas)) {
			map.put("data", equipmentAreas);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().print(returnData);
	}
	
	@RequestMapping(value = "/selectEquiClassifyAndAreaId", method = RequestMethod.GET)
	@SystemLog(module = "查询隧道下所有设备分类及事故区域", methods = "查询确定隧道下的所有设备分类和事故区域")
	public void selectEquiClassifyAndAreaId(Equipments equipments, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String returnData = "";
		Map<String, Object> map = new HashMap<String, Object>();
		// 查询确定隧道下某个事故区域的监控区域和它下面的触发设备
		List<Equipments> equipmentAreas = equipmentsLogic.selectEquiClassifyAndAreaId(equipments);
		
		if (JudgeNullUtil.iList(equipmentAreas)) {
			map.put("data", equipmentAreas);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().print(returnData);
	}
	

	/**
	 * 模拟websocket接口往前端发送数据,以后的正式环境需要删除
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/websocketInterface", method = RequestMethod.GET)
	@ResponseBody
	@SystemLog(module = "设备管理", methods = "查询路段下所有隧道的摄像机信息方法")
	public void websocketInterface(HttpServletRequest request, HttpServletResponse response) throws IOException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String, Object> firePlanWebSocketContent = new HashMap<String, Object>();		
		String accidentCameraCode = "";
		//模拟触发设备信息
		String triggerEquipmentCode = "EQN9JUJ";
		EquipmentsAttr equipmentsAttr = new EquipmentsAttr();
		equipmentsAttr.setEquipmentCode(triggerEquipmentCode);
		//查询出来的报警设备信息
		Equipments alarmEquipment = equipmentsLogic.selectPositionByCode(equipmentsAttr);
		alarmEquipment.setEquipmentName(alarmEquipment.getName());
		alarmEquipment.setAccidentType("火灾");
		//查询报警设备所处的区域,返回的是摄像机设备的信息
		Equipments cameraEquipment = equipmentsLogic.selectEquipArea(equipmentsAttr);
		if (cameraEquipment != null) {
			accidentCameraCode = cameraEquipment.getCode();
		}
		
		// 查询摄像机设备
//		List<Equipments> cameraEquipmentsBySeCode = equipmentsLogic.selectCameraEquipmentsBySeCode();
		List<Equipments> cameraEquipmentsBySeCode = equipmentsLogic.selectAllClassifyTunnelsAndAccidentArea();
		// 获取隧道事故时的紧急联系人方式
		PredictionContacter predictionContacter = new PredictionContacter();
		List<PredictionContacter> predictionContacters = predictionRuleTableDao
				.selectPredictionContacter(predictionContacter);

		// 返回事故类型
		firePlanWebSocketContent.put("accidentType", "火灾");
		//往前端返回触发预案的设备信息
		firePlanWebSocketContent.put("predictionRules", alarmEquipment);
		// 定位警报的摄像机的设备code值
		firePlanWebSocketContent.put("accidentCameraCode", accidentCameraCode);
		firePlanWebSocketContent.put("sectionsAndCameraEquipments", cameraEquipmentsBySeCode);
		firePlanWebSocketContent.put("predictionContacters", predictionContacters);

		ObjectMapper mapper1 = new ObjectMapper();
		mapper1.setSerializationInclusion(Include.NON_NULL);
		sendPredictionAlarmWebSocket(mapper1.writeValueAsString(firePlanWebSocketContent));
	}

	/**
	 * websocket推送数据方法
	 * @param content
	 * @return
	 */
	public int sendPredictionAlarmWebSocket(String content) {
		// 遍历所有连接客户工单WebSocket 推送对话
		Iterator<Map.Entry<String, PredictionAlarmWebsocket>> firePlanAlarmWebsocket = PredictionAlarmWebsocket.webSocketMap
				.entrySet().iterator();
		while (firePlanAlarmWebsocket.hasNext()) {
			Map.Entry<String, PredictionAlarmWebsocket> firePlanAlarm = firePlanAlarmWebsocket.next();
			try {
				firePlanAlarm.getValue().sendMessage(content);
			} catch (IOException e) {
			}
		}
		return 0;
	}
	
}
